package cn.lf.android.lawfirm.inputsource;

import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.zhy.autolayout.AutoRelativeLayout;

import java.util.ArrayList;
import java.util.List;

import cn.lf.android.lawfirm.BaseActivity;
import cn.lf.android.lawfirm.R;
import cn.lf.android.lawfirm.inputsource.conntroller.AcceptingDepartmentController;
import cn.lf.android.lawfirm.inputsource.conntroller.InputController;
import cn.lf.android.lawfirm.inputsource.conntroller.SourcePeopleController;
import cn.lf.android.lawfirm.inputsource.model.AcceptingDepartment;
import cn.lf.android.lawfirm.inputsource.model.Entrusting;
import cn.lf.android.lawfirm.inputsource.model.EntrustingTellEntity;
import cn.lf.android.lawfirm.inputsource.model.People;
import cn.lf.android.lawfirm.inputsource.view.AddEntrustingAdapter;
import cn.lf.android.lawfirm.inputsource.view.AddPeopleAdapter;
import cn.lf.android.lawfirm.inputsource.view.EntrustingAdapter;
import cn.lf.android.lawfirm.utils.DebugLog;
import cn.lf.android.lawfirm.utils.SPUtil;
import cn.lf.android.lawfirm.utils.timepicker.TimePicker;
import cn.lf.android.lawfirm.view.NoScrollListView;

import static cn.lf.android.lawfirm.MyApplication.context;
import static cn.lf.android.lawfirm.R.id.eb_tv_right;
import static cn.lf.android.lawfirm.inputsource.conntroller.AcceptingDepartmentController.AcceptingDepartmentCallback;

/**
 * 录入案源页
 */
public class InputSourceActivity extends BaseActivity implements AcceptingDepartmentCallback, InputController.InputCallback {
    /**
     * 返回
     **/
    private ImageButton img_left;
    /**
     * 标题
     **/
    private TextView mtitle;
    private TextView tv_right;
    /**
     * 拟委托方部分
     **/
    private AutoRelativeLayout rl_entrusting;
    /**
     * 委托人类型部分
     **/
    private AutoRelativeLayout rl_clientType;
    private TextView content_clientType;
    /**
     * 案件来源类型
     **/
    private AutoRelativeLayout rl_case_from;
    private TextView case_from;
    /**
     * 委托方联系方式
     **/
    private AutoRelativeLayout rl_entrustingtell;
    /**
     * 对方当事人部分
     **/
    private AutoRelativeLayout rl_opposingparty;
    /**
     * 案件受理部门部分
     **/
    private AutoRelativeLayout rl_caseAcceptDepartment;
    private List<AcceptingDepartment> departmentList = new ArrayList<AcceptingDepartment>();
    private TextView department_textview;
    /**
     * 案源人
     **/
    private TextView content_people;
    private AutoRelativeLayout rl_people;
    /**
     * 拟委托方listView
     **/
    private NoScrollListView noScroll_entrusting;
    private EntrustingAdapter mEntrustingAdapter;
    private ArrayList<Entrusting> list_entrusting = new ArrayList<Entrusting>();
    /**
     * 拟委托方联系方式listView
     **/
    private NoScrollListView noScroll_entrustingtell;
    /**
     * 拟委托方联系方式list
     **/
    private ArrayList<EntrustingTellEntity> list_entrusting_tell = new ArrayList<EntrustingTellEntity>();
    /**
     * 拟委托方联系方式adapter
     **/
    private AddEntrustingAdapter entrustingTellAdapter;
    /**
     * 对方当事人listView
     **/
    private NoScrollListView noScroll_opposingparty;
    /**
     * 对方当事人list
     **/
    private ArrayList<People> list_party;
    /**
     * 对方当事人adapter
     **/
    private AddPeopleAdapter partyAddPeopleAdapter;
    /**
     * 案件受理部门list
     **/
    private List<AcceptingDepartment> beans = new ArrayList<AcceptingDepartment>();
    /**
     * 案件名称
     **/
    private EditText et_name;
//--参数--
    /**
     * 受理部门编号
     **/
    private String department = "";
    /**
     * 简要描述
     **/
    private String brief = "";
    /**
     * 案件名称
     **/
    private String caseName;
    /**
     * 案源人编号（如果为自定义案源人为空）
     **/
    private String caseSourcePeople = "";
    /**
     * 拟委托方。格式为：委托方1ID（自定义-0）,委托方名称,委托方类型（单位-1/个人-2）,联系人名字,联系人电话/委托方2ID,委托方名称,委托方类型（单位/个人）,联系人名字,联系人电话
     **/
    private String wtf;
    /**
     * 对方当事人。以英文逗号分隔
     **/
    private String dfdsr;
    /**
     * 委托人类型（值为：单位、个人）
     **/
    private String sourceType = "1";
    /**
     * 来源类型（值为：本所、非本所）
     **/
    private String casefrom = "本所";

    private InputController mInputController;
    private AcceptingDepartmentController mAcceptingDepartmentController;
    private TimePicker mTimePicker;
    private TimePicker mTimePicker_type;//委托人类型  (单位 个人)
    private TimePicker mTimePicker_from;//案件来源  (本所 非本所)
    /**
     * 案源人集合
     **/
    private ArrayList<People> sourcePList = new ArrayList<People>();
    private ImageView add_niweituofang;

    private People sourse_people = new People();
    private EditText custom_sourse_people;

    @Override
    public Object getContentResView() {
        return R.layout.activity_input_source;
    }

    @Override
    public void initView() {
        initTitle();
        rl_case_from = ((AutoRelativeLayout) findViewById(R.id.rl_case_from));
        case_from = ((TextView) findViewById(R.id.case_from));
        rl_entrusting = ((AutoRelativeLayout) findViewById(R.id.rl_entrusting));
        rl_clientType = ((AutoRelativeLayout) findViewById(R.id.rl_clientType));
        content_clientType = ((TextView) findViewById(R.id.content_clientType));
        rl_entrustingtell = ((AutoRelativeLayout) findViewById(R.id.rl_entrustingtell));
        rl_opposingparty = ((AutoRelativeLayout) findViewById(R.id.rl_opposingparty));
        rl_people = ((AutoRelativeLayout) findViewById(R.id.rl_people));
        rl_caseAcceptDepartment = ((AutoRelativeLayout) findViewById(R.id.rl_caseAcceptDepartment));
        department_textview = ((TextView) findViewById(R.id.department));
        content_people = ((TextView) findViewById(R.id.content_people));
        et_name = ((EditText) findViewById(R.id.et_name));
        noScroll_entrusting = ((NoScrollListView) findViewById(R.id.noscrolllistview_entrusting));
        noScroll_entrustingtell = ((NoScrollListView) findViewById(R.id.noscrolllv_entrustingtell));
        noScroll_opposingparty = ((NoScrollListView) findViewById(R.id.noscrolllistview_opposingparty));
        //--对方当事人--
        list_party = new ArrayList<People>();
        partyAddPeopleAdapter = new AddPeopleAdapter(this, list_party);
        noScroll_opposingparty.setAdapter(partyAddPeopleAdapter);
        //拟委托方联系方式
        entrustingTellAdapter = new AddEntrustingAdapter(this, list_entrusting_tell);
        noScroll_entrustingtell.setAdapter(entrustingTellAdapter);
        //拟委托方
        mEntrustingAdapter = new EntrustingAdapter(this, list_entrusting);
        noScroll_entrusting.setAdapter(mEntrustingAdapter);
        add_niweituofang = ((ImageView) findViewById(R.id.add_niweituofang));
        custom_sourse_people = ((EditText) findViewById(R.id.custom_sourse_people));
        SPUtil spUtil = new SPUtil(this);
        content_people.setText(spUtil.getUserInfo().userName);
        sourse_people.userID = spUtil.getUserAccount().getUserId();
        DebugLog.e("sourse_people.userID==" + sourse_people.userID);
        setLisenters();

    }

    private void setLisenters() {
        rl_case_from.setOnClickListener(this);
        rl_entrusting.setOnClickListener(this);
        rl_clientType.setOnClickListener(this);
        rl_entrustingtell.setOnClickListener(this);
        rl_opposingparty.setOnClickListener(this);
        rl_caseAcceptDepartment.setOnClickListener(this);
        rl_people.setOnClickListener(this);
        et_name.setOnClickListener(this);
    }

    private void initTitle() {
        img_left = (ImageButton) findViewById(R.id.img_left);
        img_left.setVisibility(View.VISIBLE);
        img_left.setOnClickListener(this);
        tv_right = ((TextView) findViewById(eb_tv_right));
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setText("保存");
        tv_right.setOnClickListener(this);
        mtitle = (TextView) findViewById(R.id.eb_tv_title);
        mtitle.setVisibility(View.VISIBLE);
        mtitle.setText("录入案源");
    }

    @Override
    public void initData() {
        //滑动退出
//        addSwipeFinishLayout();
        List<String> list_type = new ArrayList<String>();
        list_type.add("单位");
        list_type.add("个人");
        mTimePicker_type = new TimePicker(this, 1, list_type,
                new TimePicker.OnPickerCallBack() {
                    @Override
                    public void pickerDone(String timeString, long timeInMillis) {
                        content_clientType.setText(timeString);
                        if ("单位".equals(timeString)) {//单位-1/个人-2
                            sourceType = "1";
                            list_entrusting.get(0).type = 1;
                        } else if ("个人".equals(timeString)) {
                            sourceType = "2";
                            list_entrusting.get(0).type = 2;
                        }
                    }
                });
        List<String> list_from = new ArrayList<String>();
        list_from.add("本所");
        list_from.add("非本所");
        mTimePicker_from = new TimePicker(this, 1, list_from,
                new TimePicker.OnPickerCallBack() {
                    @Override
                    public void pickerDone(String timeString, long timeInMillis) {
                        case_from.setText(timeString);
                        casefrom = timeString;
                        if ("非本所".equals(timeString)) {
                            caseSourcePeople = "";
                            custom_sourse_people.setVisibility(View.VISIBLE);
                        } else {
                            custom_sourse_people.setText("");
                            custom_sourse_people.setVisibility(View.GONE);
                        }
                    }
                });
        mAcceptingDepartmentController = new AcceptingDepartmentController(this);
        mAcceptingDepartmentController.onAcceptingDepartment();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_people://安源人
                hintKbTwo();
                Intent intent = new Intent(this, TheSourcePeopleListActivity.class);
                intent.putExtra("title", "案源人");
                intent.putExtra("isBusiness", "false");
                startActivityForResult(intent, 1004);
//                mTimePicker_people.show(getWindow().getDecorView());
                break;
            case R.id.eb_tv_right://保存
                hintKbTwo();
                if (onCheak()) {
                    if (null == mInputController) {
                        mInputController = new InputController(this, this);
                    }
                    String lianxiren = "";
                    for (int i = 0; i < list_entrusting_tell.size(); i++) {
                        if (i == list_entrusting_tell.size()) {
                            lianxiren = lianxiren + list_entrusting_tell.get(i).entrustingName + "," + list_entrusting_tell.get(i).entrustingTell + ",";
                        } else {
                            lianxiren = lianxiren + list_entrusting_tell.get(i).entrustingName + "," + list_entrusting_tell.get(i).entrustingTell;
                        }
                    }
                    wtf = list_entrusting.get(0).cusID + "," + list_entrusting.get(0).name + "," + list_entrusting.get(0).type + "," + lianxiren;
                    DebugLog.e("==保存保存");
                    mInputController.onInput(department, brief, et_name.getText().toString().trim(), caseSourcePeople, wtf, dfdsr, casefrom, custom_sourse_people.getText().toString().trim());
                }
                break;
            case R.id.img_left:
                hintKbTwo();
                finish();
                break;
            case R.id.rl_entrusting:
                hintKbTwo();
                //拟委托方
                startActivityForResult(new Intent(this, QuasiCommissionedPartyActivity.class), 1001);
                break;
            case R.id.rl_case_from://案件来源
                hintKbTwo();
                mTimePicker_from.show(getWindow().getDecorView());
                break;
            case R.id.rl_clientType://委托人类型
                hintKbTwo();
                mTimePicker_type.show(getWindow().getDecorView());
                break;
            case R.id.rl_entrustingtell:
                hintKbTwo();
                //拟委托方联系方式
                startActivityForResult(new Intent(this, EntrustingTellActivity.class), 1003);
                break;
            case R.id.rl_opposingparty:
                hintKbTwo();
                //对方当事人
                startActivityForResult(new Intent(this, OpposingPartyActivity.class), 1002);
                break;
            case R.id.rl_caseAcceptDepartment://受理部门
                hintKbTwo();
                mTimePicker.show(getWindow().getDecorView());
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1001:
                    rl_clientType.setVisibility(View.VISIBLE);
                    //拟委托方选择回调
                    Entrusting entrusting = new Entrusting();
                    entrusting.name = data.getStringExtra("name");
                    entrusting.cusID = data.getStringExtra("cusID");
                    entrusting.type = data.getIntExtra("type", 0);
                    entrusting.linkmen = data.getStringExtra("linkmen");
                    entrusting.linkTel = data.getStringExtra("linkTel");
                    list_entrusting.add(entrusting);
                    if (data.getIntExtra("type", 0) == 1) {//单位-1/个人-2
                        content_clientType.setText("单位");
                    } else if (data.getIntExtra("type", 0) == 2) {
                        content_clientType.setText("个人");
                    } else if (data.getIntExtra("type", 0) == 0) {
                        content_clientType.setText("");
                        content_clientType.setHint("请选择委托人类型");
                    }
                    mEntrustingAdapter.notifyDataSetChanged();
                    //选完拟委托方后，要从后台搜索他的联系方式自动添加到拟委托方联系方式
                    if (!"0".equals(data.getStringExtra("cusID"))) {
                        EntrustingTellEntity entrustingTell = new EntrustingTellEntity();
                        entrustingTell.entrustingTell = data.getStringExtra("linkTel");
                        entrustingTell.entrustingName = data.getStringExtra("linkmen");
                        entrustingTell.wtf = data.getStringExtra("name");
                        entrustingTell.cusID = data.getStringExtra("cusID");
                        list_entrusting_tell.add(entrustingTell);
                        entrustingTellAdapter.notifyDataSetChanged();
                        rl_clientType.setClickable(false);
                    } else {
                        rl_clientType.setClickable(true);
                    }
                    setName();
                    if (list_entrusting.size() > 0) {
                        add_niweituofang.setVisibility(View.GONE);
                        rl_entrusting.setClickable(false);
                    }
                    break;
                case 1002:
                    //对方当事人
                    People people = new People();
                    people.name = data.getStringExtra("party");
                    list_party.add(people);
                    partyAddPeopleAdapter.notifyDataSetChanged();
                    setName();
                    DebugLog.e("--------对方当事人回调--------" + data.getStringExtra("party"));
                    break;
                case 1003:
                    //拟委托方联系方式
                    DebugLog.e("-----name-----" + data.getStringExtra("name"));
                    DebugLog.e("----tell----" + data.getStringExtra("tell"));
                    EntrustingTellEntity entrustingTellEntity = new EntrustingTellEntity();
                    entrustingTellEntity.entrustingName = data.getStringExtra("name");
                    entrustingTellEntity.entrustingTell = data.getStringExtra("tell");
                    list_entrusting_tell.add(entrustingTellEntity);
                    entrustingTellAdapter.notifyDataSetChanged();
                    DebugLog.e("----------拟委托方联系方式回调------------");
                    break;
                case 1004://安源人
                    sourse_people = (People) data.getSerializableExtra("people");
                    content_people.setText(sourse_people.userName);
                    break;
                default:
                    break;
            }
        }

        if (requestCode == 123) {
            //拟委托方，点击搜索框右侧对勾的回调
            Entrusting entrusting = new Entrusting();
            EntrustingTellEntity entrustingTell = new EntrustingTellEntity();
            entrusting.name = data.getStringExtra("name");
            entrusting.cusID = data.getStringExtra("cusID");
            entrusting.type = data.getIntExtra("type", 0);
            entrusting.linkmen = data.getStringExtra("linkmen");
            entrusting.linkTel = data.getStringExtra("linkTel");
            list_entrusting.add(entrusting);
            mEntrustingAdapter.notifyDataSetChanged();
        }

    }

    /**
     * 存受理部门id的集合
     */
    List<String> lsysDeptIDList = new ArrayList<>();

    @Override
    public void onSuccessed(List<AcceptingDepartment> beans) {
        departmentList.addAll(beans);
        List<String> list_strs = new ArrayList<String>();
        for (AcceptingDepartment department : departmentList) {
            list_strs.add(department.lsysDeptName);
        }
        mTimePicker = new TimePicker(this, 1, list_strs,
                new TimePicker.OnPickerCallBack() {
                    @Override
                    public void pickerDone(String timeString, long timeInMillis) {
                        String dd = department_textview.getText().toString();
                        if (dd.length() == 0) {
                            department_textview.setText(timeString);
                        } else {
                            if (!dd.contains(timeString)) {
                                department_textview.setText(dd + "," + timeString);
                            }
                        }
                        for (AcceptingDepartment bean : departmentList) {
                            if (timeString.equals(bean.lsysDeptName)) {
                                if (!lsysDeptIDList.contains(bean.lsysDeptID)) {
                                    if(department.length()==0){
                                        department = bean.lsysDeptID;
                                    }else{
                                        department = department + "," + bean.lsysDeptID;
                                    }
                                    lsysDeptIDList.add(bean.lsysDeptID);
                                }
                            }
                        }
                        DebugLog.e("编号==" + department);
                    }
                });

    }

    @Override
    public void onInputSuccessed(String str) {
        showCToast("录入成功");
        finish();
    }

    @Override
    public void onInputFailed(String errorMsg) {

    }

    @Override
    public void onFailed(String errorMsg) {
        List<String> list_strs = new ArrayList<String>();
        mTimePicker = new TimePicker(this, 1, list_strs,
                new TimePicker.OnPickerCallBack() {
                    @Override
                    public void pickerDone(String timeString, long timeInMillis) {
                    }
                });
    }

    /***
     * 案件名称
     */
    public void setName() {
        String name = "";
        dfdsr = "";
        for (int i = 0; i < list_entrusting.size(); i++) {
            if (i != list_entrusting.size() - 1) {
                name = name + list_entrusting.get(i).name + "、";
            } else {
                name = name + list_entrusting.get(i).name + "与";
            }
        }
        for (int i = 0; i < list_party.size(); i++) {
            if (i != list_party.size() - 1) {
                dfdsr = dfdsr + list_party.get(i).name + ",";
                name = name + list_party.get(i).name + "、";
            } else {
                dfdsr = dfdsr + list_party.get(i).name;
                name = name + list_party.get(i).name;
            }
        }
        et_name.setText(name);
        if (list_entrusting.size() == 0) {
            add_niweituofang.setVisibility(View.VISIBLE);
            rl_entrusting.setClickable(true);
        }
    }

    /**
     * 设置拟委托方和联系方式同步
     */
    public void setYnchronization(int position) {
        rl_clientType.setVisibility(View.GONE);
//        for (int j = 0; j < list_entrusting_tell.size(); j++) {
//            if (list_entrusting.get(position).cusID.equals(list_entrusting_tell.get(j).cusID)) {
//                list_entrusting_tell.remove(j);
//            }
//        }
        list_entrusting_tell.clear();
        entrustingTellAdapter.notifyDataSetChanged();
    }


    public Boolean onCheak() {
        if (et_name.getText().toString().trim().length() > 200) {
            showCToast("案件名称不可大于200字");
            return false;
        }
        if (casefrom.equals("本所")) {//选中非本所案源人编号为空，选中本所时案源人编号必填，长
            if (null == sourse_people) {
                showCToast("选中本所时案源人编号必填");
                return false;
            } else {
                caseSourcePeople = sourse_people.userID;
            }
        }
        if (list_entrusting.size() == 0) {
            showCToast("请添加拟委托方");
            return false;
        }
        if (list_entrusting_tell.size() == 0) {
            showCToast("请填写拟委托方联系方式");
            return false;
        }
        if (casefrom.equals("非本所") && custom_sourse_people.getText().toString().trim().length() == 0) {
            showCToast("请填写自定义案源人名字");
            return false;
        }
        if (list_entrusting.get(0).type == 0) {
            showCToast("请选择委托人类型");
            return false;
        }
        return true;
    }
}